# 统计服务
from models import db
from models.todo import Todo
from models.goal import Goal
from models.health import Habit, HabitRecord
from models.schedule import Event
from datetime import datetime, date, timedelta
from sqlalchemy import func

class StatsService:
    """统计服务类 - 提供仪表板数据"""
    
    @staticmethod
    def get_dashboard_stats():
        """获取仪表板统计数据"""
        
        # 待办统计
        todo_total = Todo.query.count()
        todo_completed = Todo.query.filter_by(completed=True).count()
        todo_pending = todo_total - todo_completed
        
        # 今日到期待办（修复：统一使用date()函数比较，与today-todos接口保持一致）
        now_utc = datetime.utcnow()
        today_date_utc = now_utc.date()  # UTC当日日期
        todo_today = Todo.query.filter(
            Todo.completed == False,
            func.date(Todo.deadline) == today_date_utc
        ).count()
        
        # 目标统计
        goal_total = Goal.query.count()
        goal_active = Goal.query.filter_by(status='进行中').count()
        goal_completed = Goal.query.filter_by(status='已完成').count()
        
        # 今日日程（修复：统一使用date()函数比较）
        event_today = Event.query.filter(
            func.date(Event.start_time) == today_date_utc
        ).count()
        
        # 习惯统计（只有完成目标才算已打卡）
        habit_total = Habit.query.filter_by(active=True).count()
        
        # 统计今天完成目标的习惯数量（修复：使用UTC日期）
        today_habits = Habit.query.filter_by(active=True).all()
        habit_today_checked = 0
        for habit in today_habits:
            record = HabitRecord.query.filter_by(habit_id=habit.id, date=today_date_utc).first()
            if record and record.count >= habit.target_count:
                habit_today_checked += 1
        
        # 本周活跃度（完成目标的打卡+完成任务）（修复：使用UTC日期）
        week_start_date = today_date_utc - timedelta(days=today_date_utc.weekday())
        
        # 统计本周完成目标的打卡天数
        week_habit_completions = 0
        all_habits = Habit.query.filter_by(active=True).all()
        for habit in all_habits:
            week_records = HabitRecord.query.filter(
                HabitRecord.habit_id == habit.id,
                HabitRecord.date >= week_start_date
            ).all()
            # 统计完成目标的天数
            week_habit_completions += sum(1 for r in week_records if r.count >= habit.target_count)
        
        # 本周完成待办（修复：统一使用日期比较）
        week_todos_completed = Todo.query.filter(
            Todo.completed == True,
            func.date(Todo.updated_at) >= week_start_date
        ).count()
        week_activity = week_habit_completions + week_todos_completed
        
        return {
            'todo': {
                'total': todo_total,
                'completed': todo_completed,
                'pending': todo_pending,
                'today': todo_today
            },
            'goal': {
                'total': goal_total,
                'active': goal_active,
                'completed': goal_completed
            },
            'event': {
                'today': event_today
            },
            'habit': {
                'total': habit_total,
                'today_checked': habit_today_checked,
                'completion_rate': round((habit_today_checked / habit_total * 100) if habit_total > 0 else 0, 1)
            },
            'week_activity': week_activity
        }
    
    @staticmethod
    def get_productivity_trends(days=7):
        """获取效率趋势（最近N天）
        
        Args:
            days: 天数
            
        Returns:
            每日的任务完成数、习惯打卡数等
        """
        # 修复：使用UTC时间
        now_utc = datetime.utcnow()
        today_date_utc = now_utc.date()
        trends = []
        
        for i in range(days):
            current_date = today_date_utc - timedelta(days=days - i - 1)
            next_date = current_date + timedelta(days=1)
            
            # 当日完成的待办（修复：统一使用date()函数比较）
            todos_completed = Todo.query.filter(
                Todo.completed == True,
                func.date(Todo.updated_at) == current_date
            ).count()
            
            # 当日的习惯打卡（完成目标才算）
            daily_habits = Habit.query.filter_by(active=True).all()
            habits_checked = 0
            for habit in daily_habits:
                record = HabitRecord.query.filter_by(habit_id=habit.id, date=current_date).first()
                if record and record.count >= habit.target_count:
                    habits_checked += 1
            
            # 当日的日程数（修复：统一使用date()函数比较）
            events_count = Event.query.filter(
                func.date(Event.start_time) == current_date
            ).count()
            
            trends.append({
                'date': current_date.isoformat(),
                'todos_completed': todos_completed,
                'habits_checked': habits_checked,
                'events_count': events_count,
                'score': todos_completed * 2 + habits_checked  # 简单的效率分数
            })
        
        return trends
    
    @staticmethod
    def get_category_distribution():
        """获取分类分布（待办、目标等的分类统计）"""
        
        # 待办分类统计
        todo_categories = db.session.query(
            Todo.category,
            func.count(Todo.id).label('count')
        ).filter_by(completed=False).group_by(Todo.category).all()
        
        # 目标分类统计
        goal_categories = db.session.query(
            Goal.category,
            func.count(Goal.id).label('count')
        ).filter_by(status='进行中').group_by(Goal.category).all()
        
        return {
            'todos': [{'category': cat, 'count': count} for cat, count in todo_categories],
            'goals': [{'category': cat, 'count': count} for cat, count in goal_categories]
        }

# 全局实例
stats_service = StatsService()

